<?php

namespace app\home\controller\lottery;

use app\BaseController;
use app\common\model\MoneyLog;
use app\common\model\TouziLottery;
use app\common\model\TouziLotteryRecord;
use app\common\model\TouziLotteryTimes;
use app\common\model\User;
use app\common\traites\PublicCrudTrait;
use think\facade\Db;
use hg\apidoc\annotation as Apidoc;

/**
 *
 * @Apidoc\Title("抽奖管理")
 * */
class Lottery extends BaseController
{
    use PublicCrudTrait;

    /**
     * @var TouziLottery
     */
    protected $model;

    public function initialize()
    {
        $this->model = new TouziLottery();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * @Apidoc\Title("奖品列表")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="array", desc="返回结果")
     */
    public function lottery_list()
    {
        // $post = $this->request->post();
        // $is_vip = ($post['is_vip']==0)?0:1;
        // 无所谓了 这个 前端没有展示了 目前

        $res = $this->model->field('*')
            // ->where(['is_vip' => $is_vip, 'is_show' => 1])
            ->where(['is_show' => 1])
            ->limit(20)
            ->order('id asc')
            ->select();
        return show($res);
    }
    /**
     * @Apidoc\Title("抽奖机会获得/减少记录")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("page", type="string",require=true, desc="页面")
     * @Apidoc\Param("limit", type="string",require=true, desc="分页限制")
     * @Apidoc\Param("start", type="string",require=true, desc="开始时间 可以不写")
     * @Apidoc\Param("end", type="string",require=true, desc="结束时间 可以不写")
     * @Apidoc\Returned("data", type="array", desc="返回数据")
     */
    public function lottery_times_record()
    {
        $uid = session('home_user.id');

        $page = $this->request->post('page', 1);//当前页
        $limit = $this->request->post('limit', 10);//每页显示数量
        $start = $this->request->post('start'); // 搜索开始时间
        $end = $this->request->post('end'); // 搜索结束时间

        $map = [];
        if (!empty($start) && !empty($end)) {
            $map[] = ['create_time', 'between', [$start, $end]];
        }

        $map[] = ['user_id', '=', $uid];

        $res = TouziLotteryTimes::page_list($map, $limit, $page, 'id desc');
        return show($res);
    }
    /**
     * @Apidoc\Title("中奖物品列表")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="array", desc="返回结果")
     */
    public function wuPin_list()
    {
        $uid = session('home_user.id');
        $post = $this->request->post();
        $is_vip = ($post['is_vip']==0)?0:1;

        $res = (new TouziLotteryRecord())->field('*')
            ->where(['is_vip' => $is_vip, 'user_id'=>$uid, 'is_juanzeng' => 0, 'is_lingqu' => 0])
            ->order('id asc')
            ->select();
        return show($res);
    }

    /**
     * @Apidoc\Title("物品领取或者捐赠")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="array", desc="返回结果")
     */
    public function ling_or_juan()
    {
        $post = $this->request->post();
        $record_id = $post['id'];
        $recordInfo = (new TouziLotteryRecord())->find($record_id)->toArray();

        
        if($recordInfo['is_vip']==0){
            if($recordInfo['is_juanzeng'] == 1){
                return show([], config('ToConfig.http_code.error'), '请勿重复操作');
            }
            Db::startTrans();
            // 捐赠物品
            // 修改当前状态
            $record_update = [];
            $record_update['id']=$recordInfo['id'];
            $record_update['is_juanzeng']=1;
            (new TouziLotteryRecord())->update($record_update);

            // 修改用户 捐赠金
            $prizeId = $recordInfo['jiangpin_id'];
            $prizeInfo = (new TouziLottery())->find($prizeId)->toArray();
            $juan_money = $prizeInfo['juan_money'];
            $uid = $recordInfo['user_id'];
            $user = (new User())->where('id', $uid)->find();
            (new User())->where(['id'=>$uid])->inc('money_juanzeng',$juan_money)->update();
            // 写入日志 
            MoneyLog::flowing(1, 1, 1, 116, $user, $juan_money, $recordInfo['id'], '用户捐赠[' . $recordInfo['jiangpin_name'] . '],获得捐赠金:' .$juan_money, 'money_juanzeng');
            Db::commit();
        }else{

            /////////////////////////
            // 增加一个判断 不是 vip 用户 不能领取
            $uid = session('home_user.id');
            $user = (new User())->find($uid);
            // return show($user->vip_grade);
            if($user->vip_grade ==0){
                return show([], config('ToConfig.http_code.error'), '请升级为慈善大使');
            }
            // 增加结束

            if($recordInfo['is_lingqu'] == 1){
                return show([], config('ToConfig.http_code.error'), '请勿重复操作');
            }
            Db::startTrans();
            // 自用物品 
            // 修改当前状态
            $record_update = [];
            $record_update['id']=$recordInfo['id'];
            $record_update['is_lingqu']=1;
            (new TouziLotteryRecord())->update($record_update);
            Db::commit();            
        }
        return show([]);
    }

    /**
     * @Apidoc\Title("抽奖")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="array", desc="返回结果")
     */
    public function lottery_draw()
    {
        $uid = session('home_user.id');
        $user = User::find($uid);

        // 检查用户抽奖次数
        if ($user['choujiang_times'] <= 0) {
            return show([], config('ToConfig.http_code.error'), '很遗憾，你没有抽奖次数了。');
        }

        Db::startTrans();
        try {
            // 从数据库中读取奖品信息
            // if($user->vip_grade == 1){
            //     $prizes = $this->model->where('is_ky_zhongjiang', 1)->order('id', 'asc')->select()->toArray();
            // }else{
            //     $prizes = $this->model->where(['is_ky_zhongjiang'=>1,'is_vip'=>0])->order('id', 'asc')->select()->toArray();
            // }

            // 不区分等级进行中奖了 
            $prizes = $this->model->where('is_ky_zhongjiang', 1)->order('id', 'asc')->select()->toArray();
            $totalRate = array_sum(array_column($prizes, 'zhongjiang_rate'));
            $last = end($prizes); //最后一个奖项            
            $maxWinnersPerDay = getSystemConfig('choujiang_day_max_times');// 当日最大中奖次数            
            $winnersToday = TouziLotteryRecord::whereDay('create_time')->count();// 获取今天已经中奖的人数

            
            if ($winnersToday > $maxWinnersPerDay) {
                // 达到最大中奖次数 就是再接再厉
                TouziLotteryRecord::create([
                    'user_id' => $uid,
                    'user_name' => $user['user_name'],
                    'jiangpin_id' => $last['id'],
                    'jiangpin_name' => $last['jiangpin_name'],
                    'is_zhongjiang' => $last['is_zhongjiang'],
                    'is_vip' => $last['is_vip'],
                    'create_time' => date('Y-m-d H:i:s'),
                    'is_show' => 0,
                ]);
                TouziLotteryTimes::create([
                    'user_id' => $uid,
                    'send_times' => -1,
                    'create_time' => date('Y-m-d H:i:s'),
                    'mark' => '抽奖减少次数',
                ]);
                // 减少用户的抽奖次数
                User::decreaseTimes($uid);

                Db::commit();
                return show($last);
            }

            $accumulatedRate = 0;
            $rand = mt_rand(1, $totalRate);

            foreach ($prizes as $prize) {
                $accumulatedRate += $prize['zhongjiang_rate'];
                if ($rand <= $accumulatedRate) {
                    // 记录次数减少
                    TouziLotteryTimes::create([
                        'user_id' => $uid,
                        'send_times' => -1,
                        'create_time' => date('Y-m-d H:i:s'),
                        'mark' => '抽奖减少次数',
                    ]);
                    // 减少用户的抽奖次数
                    User::decreaseTimes($uid);

                    // 如果中奖类型是 现金 直接进行 发放了
                    if($prize['is_kejuan'] == 1){
                        $money_type = $prize['money_type'];
                        $money_nums = $prize['juan_money'];
                        // 增加共富金
                        User::increaseBy($money_type, $uid, $money_nums);
                        MoneyLog::flowing(1, 1, 1, 305, $user, $money_nums, 0, '抽奖赠送', $money_type);
                    
                        // 记录中奖信息到数据库 用户免费操作的
                        TouziLotteryRecord::create([
                            'user_id' => $uid,
                            'user_name' => $user['user_name'],
                            'jiangpin_id' => $prize['id'],
                            'jiangpin_name' => $prize['jiangpin_name'],
                            'is_zhongjiang' => $prize['is_zhongjiang'],
                            'is_vip' => $prize['is_vip'],
                            'create_time' => date('Y-m-d H:i:s'),
                            'is_show' => 1,
                            // 各种金的控制
                            'is_lingqu'=>1,
                            'is_fafang'=>1,
                            'is_juanzeng'=>1,
                        ]);
                    }else{
                        // 记录中奖信息到数据库  用户可以操作的
                        TouziLotteryRecord::create([
                            'user_id' => $uid,
                            'user_name' => $user['user_name'],
                            'jiangpin_id' => $prize['id'],
                            'jiangpin_name' => $prize['jiangpin_name'],
                            'is_zhongjiang' => $prize['is_zhongjiang'],
                            'is_vip' => $prize['is_vip'],
                            'create_time' => date('Y-m-d H:i:s'),
                            'is_show' => 1,
                        ]);
                    }

                    
                    Db::commit();
                    return show($prize);
                }
            }

            // 没抽中 就是再接再厉
            TouziLotteryRecord::create([
                'user_id' => $uid,
                'user_name' => $user['user_name'],
                'jiangpin_id' => $last['id'],
                'jiangpin_name' => $last['jiangpin_name'],
                'is_zhongjiang' => $last['is_zhongjiang'],
                'is_vip' => $last['is_vip'],
                'create_time' => date('Y-m-d H:i:s'),
                'is_show' => 1,
            ]);
            TouziLotteryTimes::create([
                'user_id' => $uid,
                'send_times' => -1,
                'create_time' => date('Y-m-d H:i:s'),
                'mark' => '抽奖减少次数',
            ]);
            // 减少用户的抽奖次数
            User::decreaseTimes($uid);
            Db::commit();
            return show($last);
        } catch (\Exception $e) {
            Db::rollback();
            return show([], config('ToConfig.http_code.error'), $e->getMessage());
        }
    }

    /**
     * @Apidoc\Title("中奖记录")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="array", desc="返回结果")
     */
    public function lottery_record()
    {
        $res = TouziLotteryRecord::where('is_show', 1)->limit(10)->order('id desc')->select()->toArray();
        return show($res);
    }

    /**
     * @Apidoc\Title("抽奖记录 个人抽奖记录")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="array", desc="返回结果")
     */
    public function lottery_draw_record()
    {
        $uid= session('home_user.id');
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件
        $post = array_filter($this->request->post());
        $where=array();
        $where[]=array('user_id','=',$uid);
        $Model=new TouziLotteryRecord();

        $res=$Model->where($where)
            ->order('create_time desc')
            ->paginate(['list_rows' => $limit, 'page' => $page], false)
            ->each(function($item, $key){
            });
        return show($res);
    }
}
